<template>
  <div class="template-flex">
    <a-row>
      <a-col :span="3">
        <div class="template-left">
          <div class="left-head">
            <div class="left-tip"></div>
            <div class="template-title">条款分类</div>
          </div>
          <div>
            <a-menu style="width: 100%" mode="inline" v-model:selectedKeys="selectedKeys">
              <a-menu-item v-for="item in templateTypesData" :key="item.clauseType" @click="menuClick(item)">
                <a-anchor :affix="false" @click="handleAnchorClick" :get-current-anchor="getCurrentAnchor">
                  <a-anchor-link :href="item.href">
                    <template #title>
                      {{`${item.clauseType}(${item.count})`}}
                    </template>
                  </a-anchor-link>
                </a-anchor>
              </a-menu-item>
            </a-menu>
          </div>
        </div>
      </a-col>
      <a-col :span="16">
        <div class="template-middle">
          <div class="template-header">
            <div class="template-title">合同模板</div>
            <div>
              <a-button class="search-btn1" @click="exportTemple">
                <template #icon>
                  <PlusOutlined />
                </template>
                导出</a-button>
            </div>
          </div>
          <div class="template-pdf">
            <div v-if="jsPdf">
              <PdfPreview v-if="viewType === 'pdf'" :pdf-url="jsPdf"/>
              <WordView v-if="viewType === 'docx'" :word-url="jsPdf"/>
            </div>
            <EmptyDefault v-else :descriptionInfo="'暂无模板文件'"></EmptyDefault>
          </div>
        </div>
      </a-col>
      <a-col :span="5">
        <div class="template-right">
          <div class="template-header">
            <div class="template-title">条款内容</div>
            <div>
              <a-button class="search-btn1" @click="goAdd">
                <template #icon>
                  <PlusOutlined />
                </template>
                新增</a-button>
            </div>
          </div>
          <div class="template-list" id="templateList">
            <div :class="{'template-item':  true, 'template-item-active':linkId === index }"
                 :id="temmplateItemId(index)"
                 v-for="(items, index) in templateClauseData"
                 :key="`${index}-${items.clauseType}`">
              <div class="item-title">
              <span>{{items.clauseType}}</span>
                <a-tooltip>
                  <template #title>复制</template>
                  <CopyOutlined :style="{color: '#0062AD'}" @click="copy(items.clauseContent)"/>
                </a-tooltip>
              </div>
              <div class="item-subtitle">
                {{items.clauseContent}}
               </div>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <AddClause ref="addClauseTemp" :templeId="templateData.id" @saveMemForm="onSave"/>
    <a-modal v-model:visible="downVisible" title="导出模板" @ok="downHandleOk">
      <a-form :model="downForm" labelAlign="left">
        <div class="form-item-border">
          <a-form-item label="起始页码" name="startPage">
            <a-input-number :bordered="false" :style="{width: '100%'}" v-model:value="downForm.startPage" placeholder="请输入起始页码" />
          </a-form-item>
        </div>
        <div class="form-item-border">
          <a-form-item label="结束页码" name="endPage">
            <a-input-number :bordered="false" :style="{width: '100%'}" v-model:value="downForm.endPage" placeholder="请输入结束页码" />
          </a-form-item>
        </div>
      </a-form>
      <template #footer>
        <div class="from-btn-right">
          <a-button key="back" class="border-btn" @click="closeDownModel">取消</a-button>
          <a-button key="submit" @click="downHandleOk" class="search-btn1">下载</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, watch} from 'vue'
const { proxy  } = getCurrentInstance()
import {PlusOutlined, CopyOutlined} from '@ant-design/icons-vue';
import PdfPreview from '@/components/PdfView/PdfPreview.vue'
import WordView from '@/components/WordView/WordView.vue'
import EmptyDefault from '@/components/EmptyDefault/EmptyDefault.vue'
import AddClause from './AddClause.vue'
const selectedKeys = ref(['1'])
const viewType = ref('')
const jsPdf = ref('')
const addClauseTemp = ref()
const templateData = ref({
  path: '',
  id: ''
}) //模板数据
const templateClauseData = ref([]) //模板条款信息
const templateTypesData = ref([]) //模板条款类型
const downVisible = ref(false)
import { useRoute } from 'vue-router';
import {message} from "ant-design-vue";
const route = useRoute()
const downForm = ref({
  id:'',
  startPage: '',
  endPage: ''
})
watch(() => templateData.value, (newVal) => {
  console.log('数据更新了模板数据信息', newVal)
  templateData.value = newVal
  if (newVal.path) {
    let houzui = newVal.path.substring(newVal.path.lastIndexOf('.'), newVal.path.length).toLowerCase()
    let res1 = ['.pdf'].includes(houzui)
    if (res1) {
      viewType.value = 'pdf'
    } else {
      viewType.value = 'docx'
    }
    jsPdf.value = newVal.path
  }
})
watch(() => templateClauseData.value, (newVal) => {
  console.log('数据更新了模板条款信息', newVal)
  templateClauseData.value = newVal
})
watch(() => templateTypesData.value, (newVal) => {
  // changeVal(newVal)
  templateTypesData.value = newVal
  console.log('数据更新了模板条款类型', newVal)
})
const changeVal = (newVal) => {
  if (newVal.length > 0 && templateClauseData.value.length > 0) {
    let newList = []
    newVal.map(mItem => {
      templateClauseData.value.map((temItem, index) => {
        newList.push(Object.assign({}, mItem, {
          href:mItem.clauseType === temItem.clauseType? `#item_${index}` : '#'
        }))
      })
    })
    const unique = [];
    for (const item of newList) {
      const duplicate = unique.find(
          (obj) => obj.clauseType === item.clauseType && obj.href === item.href
      );
      if (!duplicate) {
        unique.push(item);
      }
    }
    for (let i= 0; i <= unique.length; i++) {
      if (unique[i]) {
        if (unique[i].clauseType === unique[i + 1].clauseType) {
          if (unique[i].href === '#') {
            unique.splice(i,1)
          } else {
            unique.splice(i+1,1)
          }

        }
      }
    }
    console.log('最新你的', unique)
    templateTypesData.value = unique
  } else {
    templateTypesData.value = newVal
  }
  templateTypesData.value = newVal
}
const goAdd = () => {
  addClauseTemp.value.showModal()
}
const getTempleInfo = () => {
  proxy.$api.getTemplateInfo({id: route.query.id}).then(res => {
    console.log('合同模板详情', res)
    templateData.value = res.resultObject.data
    templateClauseData.value = res.resultObject.templateClause
    templateTypesData.value = res.resultObject.clauseTypes
  })
}

const onSave = (val) => {
  if(val) {
    console.log('更新了数据么')
    getTempleInfo()
  }
}
/**
 * 导出
 * */
const exportTemple = () => {
 // downVisible.value = true
  if (jsPdf.value) {
    window.location.href = jsPdf.value
    message.success('请查看浏览器下载列表')
  }
}
const closeDownModel = () => {
  downVisible.value = false
  downForm.value.startPage = ''
  downForm.value.endPage = ''
}
const downHandleOk = () => {
  Object.assign(downForm.value, {
    id: templateData.value.id
  })
  proxy.$api.getDownloadContractWithPageNum(downForm.value).then(res => {
    if (res.resultCode === 0) {
      message.success('导出成功，请到导出记录中下载')
    }
  })
}
/**
 * 复制内容
 * */
const copy = (item) => {
  const input = document.createElement('input')
  document.body.appendChild(input)
  input.setAttribute('value', item)
  input.select()
  if (document.execCommand('copy')) {
    document.execCommand('copy')
    message.success('复制成功')
  }
  document.body.removeChild(input)
}
const linkId = ref('')
const getCurrentAnchor = () => {
  return '#templateList'
}
const menuClick = (item) => {
  for (let [index, titem] of templateClauseData.value.entries()) {
    if (item.clauseType === titem.clauseType) {
      linkId.value = index
      break
    }
  }
  console.log('点击的是',  linkId.value)
}
const handleAnchorClick = (e, link) => {
  console.log('点击的', e, link)
  // 阻止 a 标签默认事件
  e.preventDefault()
  if (link.href) {
    // 找到锚点对应得的节点
    let element = document.getElementById(link.href)
    // 如果对应id的锚点存在，就跳滚动到锚点顶部
    element && element.scrollIntoView({ block: 'end', behavior: 'smooth', alignToTop: 'false' })
  }
}
const temmplateItemId = (index) => {
  return `item_${index}`
}
onMounted(() => {
  getTempleInfo()
})
</script>

<style lang="scss" scoped>
.template-flex {
  background: #ffffff;
  border-radius: 4px;
  .template-left {
    .left-head {
      padding: 32px 24px 10px 24px;
      position: relative;
      .left-tip {
        width: 32px;
        height: 32px;
        background: #1CCAD9;
        position: absolute;
        left: 0;
        top:0;
        clip-path: polygon(0 0, 0 100%, 100% 0, 100% 0);
      }
    }
  }
  .template-right {
    padding: 32px 24px;
    .template-list {
      margin-top: 18px;
      overflow-y: auto;
      .template-item {
        padding: 20px 16px;
        width: 100%;
        height: 148px;
        background: #f5f8fa;
        border: 1px solid #0062ad;
        border-radius: 4px;
        text-align: left;
        color: #2c3749;
        margin-bottom: 16px;
        .item-title {
          font-size: 16px;
          font-weight: bold;
          line-height: 22px;
          display: flex;
          justify-content: space-between;
          width: 100%;
        }
        .item-subtitle {
          margin-top: 16px;
          font-size: 14px;
          font-weight: 400;
          line-height: 20px;
          height: 80px;
          overflow-y:auto;
         // text-overflow:ellipsis;
         // display:-webkit-box;
         //-webkit-line-clamp:4;
         //-webkit-box-orient:vertical;
        }
      }
    }
  }
  .template-middle {
    border-left: 1px solid #DCDEE0;
    border-right: 1px solid #DCDEE0;
    padding: 32px 24px;
    .template-pdf {
      width: 100%;
      height: 1000px;
      margin-top: 15px;
    }
  }
  .template-title {
    font-size: 20px;
    font-weight: bold;
    text-align: left;
    color: #2c3749;
    line-height: 28px;
  }
}
.template-header {
  display: flex;
  justify-content: space-between;
}
.template-item-active {
  border: 1px solid #F5001D !important;
}
</style>
